package com.spring.security.project.service.impl;

import com.spring.security.project.dao.UserMapper;
import com.spring.security.project.po.AuthorityPO;
import com.spring.security.project.po.UserPO;
import com.spring.security.project.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserPO getUserInfo(String name) {
        UserPO user = userMapper.getUserByUsername(name);
        if (Objects.isNull(user)){
            throw new UsernameNotFoundException("用户不存在！");
        }
        Long id = user.getId();
        AuthorityPO authorities = userMapper.getAuthorityById(id);
        String authority = authorities.getAuthority();
        List<GrantedAuthority> roles = getRoles(authority);
        user.setAuthorities(roles);
        return user;
    }

    //处理权限
    private List<GrantedAuthority> getRoles(String authority){
        List<GrantedAuthority> authorities = new ArrayList<>();
        String[] split = authority.split(",");
        for (int i = 0; i < split.length; i++) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(split[i]);
            authorities.add(simpleGrantedAuthority);
        }
        return authorities;
    }
}
